package com.wayne.leetcode.problems;

import java.util.ArrayDeque;
import java.util.Deque;

public class Solution402 {
  public static String removeKdigits(String num, int k) {
    int len = num.length();
    if (k >= len) return "0";
    Deque<Character> stack = new ArrayDeque<>();
    char[] chars = num.toCharArray();
    for (int i = 0; i < len; i++) {
      while (!stack.isEmpty() && stack.peekLast() > chars[i] && k > 0) {
        stack.removeLast();
        k--;
      }
      stack.addLast(chars[i]);
    }
    StringBuilder sb = new StringBuilder();
    for (Character c : stack) {
      sb.append(c);
    }
    String res;
    if (k > 0) {
      res = sb.substring(0, sb.length() - k);
    } else {
      res = sb.toString();
    }
    while (true) {
      if (res.charAt(0) == '0' && res.length() > 1) {
        res = res.substring(1);
        continue;
      }
      break;
    }
    return res;
  }

  public static void main(String[] args) {
    System.out.println(removeKdigits("10", 1));
  }
}